<template>
  <div
    class="tim"
    :class="{'sdk-loading': loadingSDK}"
  >
    <van-loading
      v-if="loadingSDK"
      type="spinner"
    />
    <template v-else>
      <!-- <div
        class="more"
      >
        <span
          v-if="!finished"
          class="has-more"
          @click="onLoadHistoryMsg"
        >
          查看更多
        </span>
        <span v-else>没有更多了</span>
      </div> -->
      <div
        ref="list"
        class="tim-list"
      >
        <div class="xxx">
          <ChatItem
            v-for="item in chatMsgList"
            :key="item.ID"
            :msg="item"
          />
        </div>
      </div>
      <div
        v-if="topMostMsg.ID"
        class="top-most"
      >
        <ChatItem
          :key="topMostMsg.ID"
          :msg="topMostMsg"
        />
        <van-icon
          name="close"
          class="close-icon"
          @click="clearTopMostMsg"
        />
      </div>
    </template>
  </div>
</template>
<script lang="ts">
import Vue from 'vue'
import TIM from 'tim-js-sdk'
// import COS from 'cos-js-sdk-v5'
import ChatItem from './Chat/ChatItem.vue'
let tim: TIM
export default Vue.extend({
  components: {
    ChatItem,
  },
  // eslint-disable-next-line vue/require-prop-types
  props: ['groupId'],
  data () {
    const userId = localStorage.getItem('userId')!
    return {
      chatMsgList: [] as any[],
      loadingSDK: true,
      loading: false,
      finished: false,
      nextReqMessageID: '',
      curConversationID: `GROUP${this.groupId}`,
      userInfo: this.$store.state.userInfo as UserInfoState,
      sendingMsg: false,
      topMostMsg: {},
      userId: '',
      userSig: '',
    }
  },
  // computed: {
  //   userNickName (): string {
  //     if (this.userInfo.RealName) {
  //       return this.userInfo.RealName.replace(/^(.)(.*)(.)$/, (sub, arg1, arg2, arg3) => {
  //         return `${arg1}*${arg2.length > 0 ? arg3 : ''}`
  //       })
  //     }
  //     return this.userInfo.Phone.replace(/^(\d{3})\d{4}/, '$1*')
  //   },
  // },
  created () {
    // @ts-ignore
    window.tim = tim = TIM.create({
      SDKAppID: +process.env.VUE_APP_FAKE_SDKAppID!,
    })
    tim.setLogLevel(1)
    // tim.setLogLevel(process.env.NODE_ENV !== 'production' ? 0 : 1)
    // tim.registerPlugin({ 'cos-js-sdk': COS })
    if (!this.userInfo.UserId || this.userInfo.UserId === '-1') {
      this.$axios({
        url: 'Live/VisitorSig',
        method: 'get',
      }).then(data => {
        console.log(data)
        this.userId = data.UserId
        this.userSig = data.UserSig
        this.timLogin()
      })
    } else {
      this.timLogin()
    }
    tim.on(TIM.EVENT.MESSAGE_RECEIVED, this.onReceiveMSG, this)
    tim.on(TIM.EVENT.SDK_NOT_READY, this.onNotReady, this)
  },
  mounted () {
    window.onunload = this.timLogout
  },
  beforeDestroy () {
    console.log('beforeDestroy')
    this.timLogout()
    tim.off(TIM.EVENT.MESSAGE_RECEIVED, this.onReceiveMSG)
    tim.off(TIM.EVENT.SDK_NOT_READY, this.onNotReady)
    tim.off(TIM.EVENT.ERROR, this.onSDKError)
  },
  methods: {
    onNotReady () {
      console.log('notReady')
      this.$emit('ready', false)
    },
    onSDKReady (e: any) {
      console.log('ready', e)
      this.$emit('ready', true)
      // tim.createGroup({
      //   groupID: '123456',
      //   type: TIM.TYPES.GRP_PUBLIC as string,
      //   name: 'test123456',
      // })
      this.joinGroup()
      tim.on(TIM.EVENT.ERROR, this.onSDKError)
    },
    onSDKError (e: any) {
      console.log('onSDKError', e)
    },
    filterMsg (msgList: any[]) {
      const curTextMsgList = msgList.filter(msg => msg.conversationID === this.curConversationID &&
      msg.type === TIM.TYPES.MSG_TEXT)
      let topMostMsg
      const notTopMsgList: any[] = []
      curTextMsgList.forEach(d => {
        console.log('66666', d.payload.text)
        const parseMsg = typeof d.payload.text === 'string'
          ? JSON.parse(d.payload.text) : d.payload.text
        if (!parseMsg) {
          return
        }
        const msgType = parseMsg.type
        console.log('msgType', msgType)
        switch (msgType) {
          // 普通消息
          case '1':
          case '0':
            d.payload.text = parseMsg
            notTopMsgList.push(d)
            break
          // 2禁言 3禁言恢复 5暂停直播 6直播继续 9所有画面关闭 10 主动退出软件
          case '4':
            // 置顶消息
            topMostMsg = d
            break
          case '7':
            // 直播结束 liveStatus=3
            this.$emit('liveStatus', 3)
            break
          case '8':
            // 直播开启 liveStatus=1
            this.$emit('liveStatus', 1)
            break
        }
      })
      if (topMostMsg) {
        this.$set(this.$data, 'topMostMsg', topMostMsg)
      }
      return notTopMsgList
    },
    onReceiveMSG (e: any) {
      console.log('onReceiveMSG', e)

      const msgList = this.filterMsg(e.data)
      this.chatMsgList.push(...msgList)
      if (msgList.length) {
        this.scrollMessageListToButtom()
      }
    },
    timLogin () {
      return tim.login({
        userID: this.userInfo.Phone || this.userId,
        userSig: this.userInfo.UserId || this.userSig,
      }).then(e => {
        console.log('loginSuc', e)
        tim.on(TIM.EVENT.SDK_READY, this.onSDKReady, this)
      }, e => {
        console.log('loginE', e)
      })
    },
    joinGroup () {
      tim.joinGroup({
        groupID: `${this.groupId}`,
      }).then(() => {
        this.loadingSDK = false
      }, e => {
        this.loadingSDK = false
      })
    },
    timLogout () {
      tim.quitGroup(`${this.groupId}`)
      tim.logout()
      window.onunload = null
    },
    sendMsg (msg: string) {
      if (this.sendingMsg) {
        // eslint-disable-next-line prefer-promise-reject-errors
        return Promise.reject()
      }

      const formatMsg = JSON.stringify({
        message: msg,
        nickName: this.userInfo.RealName,
        headImg: this.userInfo.PicUrl,
        type: '1', // 消息类型 普通消息
        senderType: '2', // 0教师 1助教 2学生
        forbidPhone: this.userInfo.Phone,
      })
      const message = tim.createTextMessage({
        conversationType: TIM.TYPES.CONV_GROUP,
        to: `${this.groupId}`,
        payload: {
          text: formatMsg,
        },
      })

      this.sendingMsg = true

      return tim.sendMessage(message).then(() => {
        this.chatMsgList.push(message)
        this.scrollMessageListToButtom(true)
        this.sendingMsg = false
      })
    },
    // 获取历史消息
    // onLoadHistoryMsg () {
    //   console.log('onLoadHistoryMsg')
    //   if (this.loading) {
    //     // eslint-disable-next-line prefer-promise-reject-errors
    //     return Promise.reject('')
    //   }
    //   this.loading = true
    //   return tim.getMessageList({
    //     conversationID: this.curConversationID,
    //     count: 15,
    //     nextReqMessageID: this.nextReqMessageID,
    //   }).then(imRes => {
    //     this.loading = false
    //     console.log('getMessageList', imRes)
    //     this.chatMsgList.unshift(...this.filterMsg(imRes.data.messageList))
    //     this.finished = imRes.data.isCompleted
    //     this.nextReqMessageID = imRes.data.nextReqMessageID
    //   })
    // },
    scrollMessageListToButtom (forceBottom: boolean = false) {
      console.log('scrollMessageListToButtom')
      setTimeout(() => {
        // const scrollBottom = forceBottom ||
        // // @ts-ignore
        //   // eslint-disable-next-line max-len
        //   (this.$refs.list.scrollHeight - this.$refs.list.clientHeight - 80) <= this.$refs.list.scrollTop
        //   // @ts-ignore
        // console.log('scrollBottom', scrollBottom)
        // if (scrollBottom) {
        if (this.$refs.list) {
          // @ts-ignore
          this.$refs.list.scrollTop = this.$refs.list.scrollHeight
        }
        // }
      }, 4)
    },
    clearTopMostMsg () {
      this.$set(this.$data, 'topMostMsg', {})
    },
  },
})
</script>

<style lang="scss" scoped>
.sdk-loading {
  display: flex;
  align-items: center;
  justify-content: center;
}
.tim {
  height: 100%;
  position: relative;
  overflow: hidden;
}
.top-most {
  position: absolute;
  left: 24px;
  top: 10px;
  right: 24px;
  background: #fff;
  z-index: 10;
  max-height: 250px;
  overflow-y: auto;
  padding: 0 20px;
  transform: translate3d(0, 0, 10px);
  -webkit-overflow-scrolling: touch;
}
.tim-list {
  @include iosScroll;
  height: 100%;
  padding: 10px 24px;
  transform: translate3d(0, 0, 1px);
}
.xxx {
  min-height: calc(100% + 1px);
}
.close-icon {
  position: absolute;
  right: 22px;
  top: 20px;
  font-size: 28px;
}
.more {
  text-align: center;
  padding: 10px 0;
  color: #666;
  font-size: 24px;
  .has-more {
    color: $primary-web;
  }
}
</style>
